package com.jinbai.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jinbai.model.ArticleListResult;
import com.jinbai.model.BlogContentResult;
import com.jinbai.model.User;
import com.jinbai.service.ArticleListResultService;
import com.jinbai.service.BlogContentResultService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/blog_content.json")
public class BlogContentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String aid = req.getParameter("aid");
        User user = null;
        HttpSession session = req.getSession(false);
        if (session != null) {
            user = (User) session.getAttribute("currentUser");
        }
        if (user == null) {
            resp.sendRedirect("/login.html");
            return;
        }
        BlogContentResultService blogContentResultService = new BlogContentResultService();
        BlogContentResult blogContentResult = blogContentResultService.blogContentResult(user, aid);
        ObjectMapper om = new ObjectMapper();
        String html = om.writeValueAsString(blogContentResult);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(html);
    }
}
